package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dyun.tool.mybatis.util.tree.TreeNodeMap;
import com.dyun.tool.mybatis.util.tree.TreeUtils;
import com.dyun.tool.ssecurity.utils.YunSecurityUtils;
import com.ruoyi.project.setting.security.LoginUser;
import com.ruoyi.project.setting.security.utils.UserUtils;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.entity.SysMenu;
import com.ruoyi.project.system.entity.SysRoleMenu;
import com.ruoyi.project.system.service.ISysMenuService;
import com.ruoyi.project.system.service.ISysRoleMenuService;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.validation.CreateGroup;
import net.dreamlu.mica.core.validation.UpdateGroup;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/system/menu")
@AllArgsConstructor
public class SysMenuController extends BaseController {

    private final ISysMenuService sysMenuService;

    private final ISysRoleMenuService sysRoleMenuService;

    /**
     * 树形菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public R list(SysMenu sysMenu) {
        // 菜单管理全显示
        List<SysMenu> menus = sysMenuService.list(new LambdaQueryWrapper<SysMenu>()
                .like($.isNotBlank(sysMenu.getMenuName()), SysMenu::getMenuName, sysMenu.getMenuName())
                .eq($.isNotNull(sysMenu.getStatus()), SysMenu::getStatus, sysMenu.getStatus())
                .eq($.isNotBlank(sysMenu.getMenuType()), SysMenu::getMenuType, sysMenu.getMenuType())
                .orderByAsc(SysMenu::getSeq));

        return success(buildMenuTree(menus));
    }

    /**
     * 树形角色可分配菜单列表
     */
    @GetMapping("/tree")
    public R tree() {
        LoginUser loginUser = UserUtils.currentLoginUser();
        // 超级管理员
        if (YunSecurityUtils.isAdmin(loginUser.getUserId())) {
            return list(new SysMenu());
        }
        return success(buildMenuTree(loginUser.getResourceList()));
    }

    /**
     * 构建前端树
     */
    private List<TreeNodeMap> buildMenuTree(List<SysMenu> menus) {
        return TreeUtils.build(menus, (menu, treeNode) -> {
            treeNode.putAll($.toMap(menu));
            // treeSelect标签
            treeNode.extra("label", menu.getMenuName());
        });
    }

    /**
     * 加载对应角色菜单列表
     */
    @GetMapping(value = "/tree/{roleId}")
    public R roleMenu(@PathVariable("roleId") Long roleId) {
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(roleId);
        List<SysMenu> roleMenu = sysMenuService.listUserMenuByRoles(roleIds);
        return success(roleMenu);
    }

    /**
     * 详情
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping("/detail")
    public R<SysMenu> detail(Long id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        return success(sysMenu);
    }

    /**
     * 新增
     */
    @SysLog(title = "菜单管理", businessType = BusinessTypeEnum.INSERT)
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @PostMapping("/add")
    public R add(@Validated(value = {CreateGroup.class}) @RequestBody SysMenu sysMenu) {
        if (!UserUtils.isAdmin(UserUtils.currentLoginUser().getUserId())) {
            return fail("请联系超级管理员新增");
        }
        return status(sysMenuService.saveIgnore(sysMenu));
    }

    /**
     * 修改
     */
    @SysLog(title = "菜单管理", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @PutMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody SysMenu sysMenu) {
        if (!UserUtils.isAdmin(UserUtils.currentLoginUser().getUserId())) {
            return fail("请联系超级管理员修改");
        }
        return status(sysMenuService.updateById(sysMenu));
    }

    /**
     * 删除
     */
    @SysLog(title = "菜单管理", businessType = BusinessTypeEnum.DELETE)
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Long id) {
        if (!UserUtils.isAdmin(UserUtils.currentLoginUser().getUserId())) {
            return fail("请联系超级管理员删除");
        }
        int childMenuNum = sysMenuService.count(new LambdaQueryWrapper<SysMenu>().eq($.isNotNull(id), SysMenu::getParentId, id));
        if (childMenuNum > 0) {
            return fail("存在子菜单,不允许删除");
        }
        int roleMenuNum = sysRoleMenuService.count(new LambdaQueryWrapper<SysRoleMenu>().eq($.isNotNull(id), SysRoleMenu::getMenuId, id));
        if (roleMenuNum > 0) {
            return fail("菜单已分配,不允许删除");
        }
        SysMenu sysMenu = new SysMenu();
        sysMenu.setId(id);
        boolean result = sysMenuService.updateById(sysMenu) && sysMenuService.removeById(id);
        return status(result);
    }
}
